package com.jiazhong.filters;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 用户登录后才能访问项目中所有子目录的内容"/el  /goods   /jstl"
 * 如果用户未登录则让用户跳转到登录页面
 */
@WebFilter({"/EL/*", "/Goods/*", "/Jstl/*"})
public class SimpleQuanXian implements Filter {
    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain) throws IOException, ServletException {
        System.out.println("权限拦截过滤器被执行");
        HttpServletRequest request = (HttpServletRequest) arg0;
        HttpServletResponse response = (HttpServletResponse) arg1;
        /**
         * 实现思路:
         *  1.从session中获取属性名为user的属性
         *  2.该属性如果存在表示用户已登录,放行继续访问目标位置
         *  3.该属性不存在则表示用户未登录,跳转到登录页面进行登录
         */
        HttpSession session = request.getSession();
        Object obj = session.getAttribute("user");
        if (obj != null) {//用户已登录
            chain.doFilter(request, response);//用户未登录
            return;
        }
        response.sendRedirect("/login.jsp");//跳转到登录页进行的登录


    }
}
